package com.pmcc.core.config.security;

import com.pmcc.core.entity.security.Employee;
import com.pmcc.core.entity.security.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.util.ArrayList;
import java.util.List;

public final class JwtUserFactory {

    static JwtTokenUtil jwtTokenUtil;

    @Autowired
    private JwtUserFactory(JwtTokenUtil jwtTokenUtil) {
        JwtUserFactory.jwtTokenUtil=jwtTokenUtil;
    }

    public static JwtUser create(Employee employee) {
        return new JwtUser(
                employee.getId(),
                employee.getUsername(),
                employee.getUserCName(),
//                employee.getOrganizations().stream().map(Organization::getId).collect(Collectors.joining(",")),
//                employee.getOrganizations().stream().map(organization -> {
//                    return StringUtils.isNotEmpty(organization.getcName())? organization.getcName():"无中文名";
//                }).collect(Collectors.joining(",")),
                employee.getOrganization().getId(),
                employee.getOrganization().getName(),
                employee.getPassword(),
                mapToGrantedAuthorities(employee.getRoleList()),
                employee.isEnabled(),
                employee.getLastPasswordResetDate()
        );
    }

    private static List<GrantedAuthority> mapTokenToGrantedAuthorities(String token) {
        List<String> authList= jwtTokenUtil.getUserAuthFormToken(token);
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        for(String  auth: authList){
            grantedAuthorities.add(new SimpleGrantedAuthority(auth));

        }
        return grantedAuthorities;
    }

    private static List<GrantedAuthority> mapToGrantedAuthorities(List<Role> roles) {
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        for(Role role: roles){
            grantedAuthorities.add(new SimpleGrantedAuthority(role.getCode()));
        }
        return grantedAuthorities;
    }
}
